<template>
  <view class="page">
    <view class="cu-bar fixed padding-lr flex align-center" :style="{'box-shadow': 'none','paddingTop': StatusBar+'px',height: CustomBar+'px'}">
      <text class="cuIcon-back text-white" style="font-size: 32rpx;" @tap="back"></text>
    </view>
    <view class="page-top">
      <image :src="imgWechatUrl+'/activity/top.png'" lazy-load style="width: 100%; height: 100;" mode="widthFix">
    </view>
    <view class="page-content" >
      <view class="content-list" :style="{'min-height':mH+'px'}">
        <view class="top-tab">
          <view class="flex justify-between" :class="{'fixed-box': isFixed}">
            <block v-for="(item,index) in nowTabs" :key="index">
              <view class="tab-item flex-sub flex flex-direction justify-center align-center text-bold text-sm" :class="[index == curIndex ? 'current' : '']"
                @click="tabSelect(index)">
                <text class="text-lg text-bold">{{item.model}}</text>
                <text class="text-xs" :class="[ index == curIndex ? 'active': '']">{{index == 0 ? i18n['抢购中']: i18n['即将开始']}}</text>
              </view>
            </block>
          </view>
        </view>
        <view class="time-box flex justify-center align-center" v-if="curIndex == 0 && lists.length != 0">
          <view class="text-333 text-bold text-df">{{i18n['距离本场结束还剩']}}</view>
          <fu-seckill-count-down ref="count" class="margin-left-sm" @refresh="init"></fu-seckill-count-down>
        </view>
        <view class="margin-top-sm">
          <block v-for="(item,index) in lists" :key="index">
            <view class="list-item flex" @click="toDeatil(item)">
              <view class="item-image radius overHidden">
				  <fu-image  :src="item.thumb" mode="aspectFill"></fu-image>
              </view>
              <view class="flex flex-direction flex-sub">
                <view class="text-cut-2 text-df text-333 text-bold item-title">{{item.name}}</view>
                <view class="flex align-center item-score">
                  <view class="out-box">
                    <view class="inner-box" :style="{width: item.rate+'%'}"></view>
                  </view>
                  <view class="score text-999">{{item.rate}}%</view>
                </view>
                <view class="flex align-center">
                  <view class="text-999 margin-right-sm text-sm">{{item.sales_sum}}{{i18n['人成功秒杀']}}</view>
                </view>
                <view class="flex justify-between margin-top-xs">
                  <view class="flex flex-direction">
                    <view class="fu-cred text-bold font-size-40 text-price">{{item | filterGoodsPrice}}</view>
                    <view class="text-999 text-price text-through margin-top-xs">{{item.market_price}}</view>
                  </view>
                  <view>
                    <view class="btn-right confirm" v-if="curIndex == 0 && item.rate !== 100">{{i18n['马上抢']}}</view>
                    <view class="btn-right bg-grey" v-if="curIndex == 0 && item.rate == 100" @tap.stop="">{{i18n['抢光了']}}</view>
                    <view class="btn-right notice" v-if="curIndex != 0 && item.message_notify == 'false'" @click.stop="handleRemind(item)">{{i18n['提醒我']}}</view>
                    <view class="btn-right notice" :class="{'cancel':curIndex != 0 && item.message_notify == 'true'}" v-if="curIndex != 0 && item.message_notify == 'true'" @click.stop="handleUnRemind(item)">{{i18n['取消提醒']}}</view>
                  </view>
                </view>
              </view>
            </view>
          </block>
          <!-- 空状态 -->
          <view v-if="lists.length == 0 && isInit"></view>
          <!-- 空列表展示 -->
          <view v-if="lists.length == 0 && isInit" class="text-xl text-center text-gray flex flex-direction align-center justify-center"
            style="padding-top:120upx;">
            <image :src="emptyImages.collection['image']" :style="{width: emptyImages.collection['width'], height: emptyImages.collection['height']}"
              mode="aspectFill"></image>
            <text class="txt">{{i18n['本场次没有商品哦']}}</text>
          </view>
        </view>
      </view>
    </view>
    <view class="page-foot">
      <view class="foot-box"></view>
    </view>
    <uni-load-more v-if="lists.length > 5"></uni-load-more>
    <fu-notwork></fu-notwork>
  </view>
</template>

<script>
  const _tabs = [{
      model: '00:00',
      text: global.i18n['即将开始'],
      start: 0
    },
    {
      model: '02:00',
      text: global.i18n['即将开始'],
      start: 2
    },
    {
      model: '04:00',
      text: global.i18n['即将开始'],
      start: 4
    },
    {
      model: '06:00',
      text: global.i18n['即将开始'],
      start: 6
    },
    {
      model: '08:00',
      text: global.i18n['即将开始'],
      start: 8
    },
    {
      model: '10:00',
      text: global.i18n['即将开始'],
      start: 10
    },
    {
      model: '12:00',
      text: global.i18n['即将开始'],
      start: 12
    },
    {
      model: '14:00',
      text: global.i18n['即将开始'],
      start: 14
    },
    {
      model: '16:00',
      text: global.i18n['即将开始'],
      start: 16
    },
    {
      model: '18:00',
      text: global.i18n['即将开始'],
      start: 18
    },
    {
      model: '20:00',
      text: global.i18n['即将开始'],
      start: 20
    },
    {
      model: '22:00',
      text: global.i18n['即将开始'],
      start: 22
    },
  ];

  import FuSeckillCountDown from "../../components/fu-seckill-count-down/fu-seckill-count-down.vue"
  export default {
    components: {
      FuSeckillCountDown
    },
    data() {
      return {
				imgWechatUrl:this.imgWechatUrl,
        emptyImages: {
          collection: {
            image: this.imgWechatUrl+'/activity/collect.png',
            width: '400rpx',
            height: '294rpx',
          },
        },
        CustomBar: this.CustomBar,
        StatusBar: this.StatusBar,
        tabs: Object.freeze(_tabs),
        curIndex: 0,
        nowTabs: [],
        lists: [],
        page: 1,
        size: 10,
        start: 0,
        status: 'more',
        isInit: false,
        seconds: 1000,
        h: '00',
        m: '00',
        s: '00',
        isFixed: false,
      };
    },

    computed:{
      mH(){
        let H = uni.getSystemInfoSync().windowHeight;
        let h = uni.upx2px(562);
        return H - h;
      }
    },
    methods: {
      // 初始化 ok
      init() {
        let nowDate = new Date();
        let _hour = nowDate.getHours();
        let _count;
        if (_hour % 2 === 0) {
          _count = _hour;
        } else {
          _count = _hour - 1;
        }
        let _startIndex = _count / 2;
        const _tabs = this.tabs.filter((item, index) => {
          return index >= _startIndex && index <= _startIndex + 5
        })
        // if (_tabs.length < 5) {
        //   let _len = 5 - _tabs.length;
        //   for (let i = 0; i < _len; i++) {
        //     _tabs.push(this.tabs[i])
        //   }
        // }
        this.nowTabs = _tabs;
        this.start = this.nowTabs[0].start;
        this.page = 1;
        this.loadData();
      },

      tabSelect(index) {
        this.curIndex = index;
        this.start = this.nowTabs[index].start;
        this.status = 'more'
        this.page = 1;
        this.loadData();
      },
      // 获取数据列表
      loadData() {
        if (this.status != 'more') return;
        this.status == 'loading';
        let data = {
          start_time: this.start,
          end_time: this.start + 2,
          page: this.page,
          list_rows: this.size,
          type: 1,
          user_id: global.userInfo && global.userInfo.id || 0,
        };
        this.$api.post(global.apiUrls.postSeckillList, data)
          .then(res => {
            if (res.statusCode == 200 && res.data.code == 1) {
              res = res.data;
              console.log('秒杀', res);
              var totalSize = res.data.total;
              var curPageData = res.data.list;
              if (this.page == 1) this.lists = [];
              this.lists = this.lists.concat(curPageData);
              if (this.lists.length < totalSize) {
                this.status = 'more';
                this.page++;
              } else {
                this.status = 'noMore';
              }
            }
            this.isInit = true;
            uni.stopPullDownRefresh();
          })
      },
      // 发送通知
      handleRemind(item) {
        const {
          goods_id,
          activity_id,
          activity_type,
          sku_id
        } = item;
        this.$util.actionAuth(() => {
          let _notifyTime = (Math.abs(this.start - 1)).toString().padStart(2, '0') + ':57'
          // #ifdef MP-WEIXIN
          uni.requestSubscribeMessage({
            tmplIds: ['x3ljpUAnxYgi-u6iQcaRuP-Z3fVoJ5o22KTDqiNhPMk'],
            complete: () => {
              this.$api.post(global.apiUrls.postSendNotice, {
                  goodsId: goods_id,
                  pageUrl: `/pages/activity/seckill/seckill-detail/index?id=${goods_id}&sku_id=${sku_id}&activity_id=${activity_id}`,
                  type: 1,
                  notifyTime: _notifyTime,
                })
                .then(res => {
                  res = res.data;
                  console.log('消息通知', res);
                  if (res.code == 1) {
                    this.$message.info(this.i18n['设置成功,将在开抢前三分钟收到提醒']);
                    this.status = 'more'
                    this.page = 1;
                    this.loadData();
                  } else {
                    this.$message.info(res.msg);
                  }
                })
                .catch(err => {
                  this.$message.info(this.i18n['该功能暂未开发']);
                  console.log(err);
                })
            },
          })
          // #endif
          // #ifdef APP-PLUS
          this.$api.post(global.apiUrls.postSendNotice, {
              goodsId: goods_id,
              pageUrl: `/pages/activity/seckill/seckill-detail/index?id=${goods_id}&sku_id=${sku_id}&activity_id=${activity_id}`,
              type: 2,
              notifyTime: _notifyTime,
            })
            .then(res => {
              res = res.data;
              console.log('消息通知', res);
              if (res.code == 1) {
                this.$message.info(this.i18n['设置成功,将在开抢前三分钟收到提醒']);
                console.log('来了')
                 this.status = 'more'
                this.page = 1;
                this.loadData();
              } else {
                this.$message.info(res.msg);
              }
            })
            .catch(err => {
              this.$message.info(this.i18n['该功能暂未开发']);
              console.log(err);
            })

          // #endif
          // #ifdef H5
          this.$message.info(this.i18n['H5不支持推送功能']);
          // #endif
        })
      },
      // 取消通知
      handleUnRemind(item) {
        console.log('来了')
        const {
          goods_id
        } = item;
        this.$util.actionAuth(() => {
          // #ifdef MP-WEIXIN
          let _notifyTime = (Math.abs(this.start - 1)).toString().padStart(2, '0') + ':57'
          this.$api.post(global.apiUrls.postCancelNotice, {
              goodsId: goods_id,
              type: 1,
              notifyTime: _notifyTime,
            })
            .then(res => {
              console.log('取消通知', res);
              if (res.data.code == 1) {
                this.$message.info(this.i18n['秒杀提醒已取消,您可能会抢不到']);
                this.status = 'more'
                this.page = 1;
                this.loadData();
              } else {
                this.$message.toast(res.data.msg);
              }
            })
            .catch(err => {
              console.log(err);
            })
          // #endif
          // #ifdef APP-PLUS
           let _notifyTime = (Math.abs(this.start - 1)).toString().padStart(2, '0') + ':57'
          this.$api.post(global.apiUrls.postCancelNotice, {
              goodsId: goods_id,
              type: 2,
              notifyTime: _notifyTime,
            })
            .then(res => {
              console.log('取消通知', res);
              if (res.data.code == 1) {
                this.$message.info(this.i18n['秒杀提醒已取消,您可能会抢不到']);
                this.status = 'more'
                this.page = 1;
                this.loadData();
              } else {
                this.$message.info(res.data.msg);
              }
            })
            .catch(err => {
              console.log(err);
            })
          // #endif
          // #ifdef H5
          this.$message.info(this.i18n['H5不支持推送功能']);
          // #endif

        })
      },
      // 去详情页
      toDeatil(item) {
        if (this.curIndex != 0) return;
        
        this.$urouter.navigateTo({
          url: '/pages/activity/seckill/seckill-detail/index',
          params: {
            goods_id: item.goods_id,
            sku_id: item.sku_id || 0,
            activity_id: item.activity_id || 0,
          }
        });
      },
      back() {
        uni.navigateBack();
      }
    },
    onLoad() {
      this.init();
    },
    onPullDownRefresh() {
      this.page = 1;
      this.status = 'more';
      this.loadData();
    },
    onReachBottom() {
      if (this.status == 'more') {
        this.loadData();
      }
    },
    onPageScroll(e) {
      let top = e.scrollTop;
      if (top > 250) {
        this.isFixed = true;
      } else {
        this.isFixed = false;
      }
    }
  }
</script>

<style lang="scss" scoped>
  .page {
    min-height: 100vh;
    background-color: #FFFFFF;
  }

  .page-top {
    width: 100%;
    height: 562rpx;
    position: relative;
    z-index: 9;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .page-content {
    position: relative;
    top: -92rpx;
    padding: 0 30rpx;
    background-color: #F43F3B;

    .content-list {
      background-color: #FFFFFF;
      padding: 92rpx 20rpx 20rpx;

      .top-tab {
        width: 100%;
        height: 100rpx;
        background-color: #FFFFFF;

        .fixed-box {
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          // #ifndef MP-WEIXIN
          // height: calc(100rpx + var(--status-bar-height));
          // padding-top: var(--status-bar-height);
          // #endif
          // #ifdef MP-WEIXIN
          // height: calc(160rpx + var(--status-bar-height));
          // padding-top: calc(60rpx + var(--status-bar-height));
          // #endif
          background-color: #FFFFFF;
          z-index: 9999;
          transition: all 0.3s;
        }

        .tab-item {
          opacity: 0.6;
        }

        .current {
          opacity: 1;
        }

        .active {
          background:$bgtheme;
          color: #fff;
          padding: 8rpx 20rpx;
          border-radius: 40rpx;
          white-space: nowrap;
        }
      }

      .time-box {
        margin-top: 10rpx;

        .hour-box,
        .min-box,
        .sec-box {
          width: 52rpx;
          height: 52rpx;
          font-size: 28rpx;
          line-height: 52rpx;
          text-align: center;
          background-color: #333333;
          color: #FFFFFF;
          border-radius: 6rpx;
        }

        .box-link {
          height: 40rpx;
          line-height: 40rpx;
          width: 16rpx;
          text-align: center;
        }
      }

      .list-item {
        margin-bottom: 20rpx;

        .item-image {
          width: 246rpx;
          height: 246rpx;
          min-width: 246rpx;
          min-height: 246rpx;
          margin-right: 20rpx;
          border-radius: 8rpx;

          image {
            width: 100%;
            height: 100%;
            border-radius: 8rpx;
          }
        }

        .item-title {
          word-break: break-all;
        }

        .item-type {
          margin: 16rpx 0;
          font-size: 24rpx;
          line-height: 33rpx;
        }

        .item-score {
          margin-top: 10rpx;

          .out-box {
            width: 220rpx;
            height: 8rpx;
            border-radius: 4rpx;
            background-color: #DBDBDB;
            margin-right: 24rpx;
          }

          .inner-box {
            height: 100%;
            width: 50%;
            border-radius: 4rpx;

            background: $bgtheme;
            /* 标准的语法（必须放在最后） */
          }
        }

        .btn-right {
          width: 120rpx;
          color: #fff;
          font-size: 20rpx;
          height: 66rpx;
          line-height: 66rpx;
          text-align: center;
          border-radius: 8rpx;
        }

        .confirm {
          background: $bgtheme;
        }

        .notice {
          background: #FFE167;

        }
        .cancel {
              background: $bgtheme;
          }
        .disabled {
          background: #FFE167;
        }
      }
    }
  }

  .page-foot {
    height: 0;
    position: relative;

    .foot-box {
      position: absolute;
      top: -92rpx;
      left: 0;
      right: 0;
      height: 92rpx;
      background-image: url($IMG_WECHAT_URL+'/activity/bottom.png');
      background-position: left bottom;
      background-size: cover;
      background-repeat: no-repeat;
    }
  }

  .text-cut-2 {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
  }

  .text-price::before {
    content: "¥";
    font-size: 80%;
    margin-right: 4upx;
  }

  .text-999 {
    color: #999999;
  }

  .text-through {
    text-decoration: line-through;
  }

  .txt {
    font-size: 28upx;
    color: $uni-text-color;
    text-align: center;
    line-height: 100upx;
    color: #999;
  }
</style>
